<?php

namespace Xrfg\Wallet\Common\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Coin;
use App\Models\Withdraw;
use Illuminate\Support\Facades\DB;
use Xrfg\Wallet\ETH\Traits\ETHHelper;
use Xrfg\Wallet\TRX\Services\TRXWallet;

class WithdrawJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use ETHHelper;

    public $withdraw;

    public function __construct(Withdraw $withdraw)
    {
        $this->withdraw = $withdraw;
    }

    public function handle()
    {
        DB::transaction(function () {
            $this->withdraw = Withdraw::lockForUpdate()->find($this->withdraw->id);
            if (Withdraw::STATUS_WAITING == $this->withdraw->status) {
                $this->withdraw->status = Withdraw::STATUS_PENDING;
                $this->withdraw->save();

                $coin = Coin::find($this->withdraw->coin_id);
                switch ($coin->name) {
                    case 'USDT':
                        (new TRXWallet(config('wallet.trx.node.wallet')))->transferTRC20($this->withdraw);
                        break;
                }
            }
        });
    }
}